import { SetupContext, computed, ref } from 'vue';
import { FilterBarProps } from '../filter-bar.props';
import { FilterItem } from '../types';
import { UseFilterItems } from '../composition/types';

export default function (props: FilterBarProps, context: SetupContext, useFilterItemComposition: UseFilterItems) {
    const { clearFilterItem, currentFilterId, filterItems, removeFilterItem, shouldShowClearButtonInFilterItem } = useFilterItemComposition;
    const disabled = ref(false);

    const filterItemClass = function (filterItem: FilterItem, index: number) {
        const classObject = {
            'f-filter-item': true,
            'f-filter-item-actived': filterItem.hasValue,
            'f-filter-item-last': index === filterItems.value.length - 1,
            'f-filter-item-edit': filterItem.id === currentFilterId.value
        } as Record<string, boolean>;
        return classObject;
    };

    const shouldShowArrowButton = computed(() => {
        return !disabled.value && props.mode === 'editable';
    });

    function onClearFilter($event: MouseEvent, targetItem: FilterItem) {
        if (props.mode === 'display-only') {
            removeFilterItem(targetItem);
        } else {
            clearFilterItem(targetItem);
        }
    }

    function onClickFilter($event: MouseEvent, data: FilterItem, index: number) {}

    return (filterItem: FilterItem, index: number) => {
        return (
            <div
                id={filterItem.id}
                class={filterItemClass(filterItem, index)}
                onClick={(payload: MouseEvent) => onClickFilter(payload, filterItem, index)}>
                <div class="f-filter-item-inner">
                    {filterItem.editor.required && <span class="f-filter-item-required text-danger">*</span>}
                    <span class="f-filter-item-text">{filterItem.fieldName}</span>
                    {filterItem.hasValue && filterItem.displayText && <span class="f-filter-item-tip">:</span>}
                    {filterItem.hasValue && filterItem.displayText && <span class="f-filter-item-content">{filterItem.displayText}</span>}
                    {shouldShowArrowButton.value && <span class="f-filter-item-arrow f-icon f-icon-arrow-chevron-down"></span>}
                </div>
                {shouldShowClearButtonInFilterItem(filterItem) && (
                    <span class="f-filter-item-clear" onClick={(payload: MouseEvent) => onClearFilter(payload, filterItem)}>
                        <span class="f-icon f-icon-close-circle"></span>
                    </span>
                )}
            </div>
        );
    };
}
